<?php

namespace App\Http\Controllers;

use App\Relation;
use App\Type;
use Illuminate\Http\Request;

class RelationController extends Controller {
	protected $model;

	public function __construct(Relation $relation) {
		$this->model = $relation;
	}

	public function index(Type $type) {
		$relation = $type->relation;
		return view('orders.relation', compact('relation'));
	}

	public function store(Type $type, Request $request) {
		$this->validate($request, [
			'map_id' => 'required',
			'order_id' => 'required',
			'contacts' => 'required',
			'phone' => 'required',
			'order_time' => 'required',
			'price' => 'required',
			'products' => 'required',
			'receipt_name' => 'required',
			'receipt_address' => 'required',
		]);
		$relation = $this->model->where('type_id', $type->id)->first();
		if (!$relation) {
			$relation = $this->model->create(array_merge($request->only(['order_id', 'contacts', 'phone', 'order_time', 'price', 'products', 'receipt_name', 'receipt_address']), ['type_id' => $type->id]));
		} else {
			$relation->order_id = $request->order_id;
			$relation->contacts = $request->contacts;
			$relation->phone = $request->phone;
			$relation->order_time = $request->order_time;
			$relation->price = $request->price;
			$relation->products = $request->products;
			$relation->receipt_name = $request->receipt_name;
			$relation->receipt_address = $request->receipt_address;
			$relation->save();
		}
		$map_id = $request->input('map_id');
		return view('orders.upload', compact('type', 'map_id'));
	}
}
